package zhenniu.best.webview.zhenniuwebview.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;

import com.blankj.utilcode.util.ToastUtils;
import com.gyf.barlibrary.ImmersionBar;

import java.io.File;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import zhenniu.best.webview.zhenniuwebview.BuildConfig;
import zhenniu.best.webview.zhenniuwebview.R;
import zhenniu.best.webview.zhenniuwebview.ZhenNiu;
import zhenniu.best.webview.zhenniuwebview.global.Constants;
import zhenniu.best.webview.zhenniuwebview.ui.view.TopMenu;
import zhenniu.best.webview.zhenniuwebview.ui.webview.Html5Webview;
import zhenniu.best.webview.zhenniuwebview.ui.webview.WebviewInterface;
import zhenniu.best.webview.zhenniuwebview.ui.webview.X5Webview;


public class WebviewActivity extends AppCompatActivity implements WebviewInterface{

    @BindView(R.id.status_bar2)
    View statusBar;
    @BindView(R.id.tm_mine_html5)
    TopMenu tm;
    @BindView(R.id.webview)
    X5Webview webview;


    //双击退出时间
    long preClickTime;
    //h5 通过webview 调用本地相册和摄像头
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private String mCurrentPhotoPath;
    private String mLastPhothPath;
    private Thread mThread;
    private static final int REQUEST_CODE_ALBUM = 0x01;
    private static final int REQUEST_CODE_CAMERA = 0x02;
    private static final int REQUEST_CODE_PERMISSION_CAMERA = 0x03;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        ZhenNiu.addActivity(this);
        init();
        setListener();
    }

    private void init() {
        //状态栏设置
        ImmersionBar.with(this)
                .statusBarView(statusBar)
                .statusBarDarkFont(false)
                .init();

        webview.setWebviewListener(this);

        //跳转到webview界面
        if (getIntent().getStringExtra(Constants.URL) != null) {

            webview.loadUrl(getIntent().getStringExtra(Constants.URL));

        }
    }

    private void setListener() {
        //标题左边箭头的监听事件
        tm.setLeftIconOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    /**
     * webview 相册 摄像 调用接口
     * @param valueCallback
     */
    @Override
    public void cameraCallBack(ValueCallback<Uri[]> valueCallback) {
        uploadMessageAboveL = valueCallback;
        uploadPicture();
    }

    @Override
    public void albumCallBack(ValueCallback<Uri> valueCallback) {
        uploadMessage = valueCallback;
        uploadPicture();
    }

    /**
     * 选择相机或者相册
     */
    public void uploadPicture() {

        AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
        builder.setTitle("请选择图片上传方式");

        //取消对话框
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                //一定要返回null,否则<input type='file'>
                //判空
                if (uploadMessage != null) {
                    //不穿图片就给 onReceiveValue 传null
                    uploadMessage.onReceiveValue(null);
                    //置空
                    uploadMessage = null;
                }
                //判空
                if (uploadMessageAboveL != null) {
                    //不穿图片就给 onReceiveValue 传null
                    uploadMessageAboveL.onReceiveValue(null);
                    //置空
                    uploadMessageAboveL = null;

                }
            }
        });

        //相机
        builder.setPositiveButton("相机", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {


                if(!TextUtils.isEmpty(mLastPhothPath)){   //图片地址不为空，意味着拍过图片
                    //上一张拍照的图片删除
                    mThread = new Thread(new Runnable() {
                        @Override
                        public void run() {

                            File file = new File(mLastPhothPath);
                            if(file!= null){
                                file.delete();
                            }
                            mHandler.sendEmptyMessage(1);

                        }
                    });

                    mThread.start();


                }else{    //第一次拍照

                    //请求拍照权限
                    if (ActivityCompat.checkSelfPermission(WebviewActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        takePhoto();
                    } else {
                        ActivityCompat.requestPermissions(WebviewActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION_CAMERA);
                    }
                }

            }
        });

        //相册
        builder.setNegativeButton("相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                chooseAlbumPic();

            }
        });

        builder.create().show();

    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            takePhoto();
        }
    };

    /**
     * 拍照
     */
    private void takePhoto() {
        //初始化stringbuilder
        StringBuilder fileName = new StringBuilder();
        //Standard Intent action that can be sent to have the camera application capture an image and return it.
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileName.append(UUID.randomUUID()).append("_upload.png");
        //文件名称
        File tempFile = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //uri: 应用包名.fileProvider , File
            Uri uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }

        mCurrentPhotoPath = tempFile.getAbsolutePath();
        startActivityForResult(intent, REQUEST_CODE_CAMERA);


    }

    /**
     * 选择相册照片
     */
    private void chooseAlbumPic() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);

    }

    /**
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ALBUM || requestCode == REQUEST_CODE_CAMERA) {

            if (uploadMessage == null && uploadMessageAboveL == null) {
                return;
            }

            //取消拍照或者图片选择时
            if (resultCode != RESULT_OK) {
                //一定要返回null,否则<input file> 就是没有反应
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;

                }
            }

            //拍照成功和选取照片时
            if (resultCode == RESULT_OK) {
                Uri imageUri = null;

                switch (requestCode) {
                    case REQUEST_CODE_ALBUM:   //相册

                        if (data != null) {
                            imageUri = data.getData();
                        }

                        break;
                    case REQUEST_CODE_CAMERA:   //相机

                        if (!TextUtils.isEmpty(mCurrentPhotoPath)) {
                            File file = new File(mCurrentPhotoPath);
                            Uri localUri = Uri.fromFile(file);
                            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                            sendBroadcast(localIntent);
                            imageUri = Uri.fromFile(file);
                            mLastPhothPath = mCurrentPhotoPath;
                        }
                        break;
                }


                //上传文件
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(imageUri);
                    uploadMessage = null;
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(new Uri[]{imageUri});
                    uploadMessageAboveL = null;

                }
            }
        }

    }

    /**
     * 权限回调函数
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults == null && grantResults.length == 0) {
            return;
        }

        if (requestCode == REQUEST_CODE_PERMISSION_CAMERA) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
                cancelFilePathCallback();
                // Permission Denied
                new AlertDialog.Builder(this)
                        .setTitle("无法拍照")
                        .setMessage("您未授予拍照权限")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent localIntent = new Intent();
                                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                                startActivity(localIntent);
                            }
                        })
                        .setCancelable(false)
                        .create().show();
            }

        }

    }

    /**
     *取消mFilePathCallback回调,防止下次点击控件没有反应
     */
    private void cancelFilePathCallback() {
        if (uploadMessage != null) {
            uploadMessage.onReceiveValue(null);
            uploadMessage = null;
        }
        if (uploadMessageAboveL != null) {
            uploadMessageAboveL.onReceiveValue(null);
            uploadMessageAboveL = null;

        }
    }

    @Override
    public void onBackPressed() {

        if (webview.canGoBack()) {   //是否可以后退
            //后退网页
            webview.goBack();
        } else {
            if (System.currentTimeMillis() - preClickTime > 2000) {
                ToastUtils.showShort(getResources().getString(R.string.exit_app));
                preClickTime = System.currentTimeMillis();
            } else { // 双击退出程序
                ZhenNiu.closeApplication();
                super.onBackPressed();
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //清楚webview缓存,销毁并释放资源
        if (webview != null) {
            webview.stopLoading();
            webview.clearHistory();
            webview.clearCache(true);
            webview.loadUrl("about:blank");
            webview.pauseTimers();
            webview = null;
        }
        mThread = null;
        mHandler = null;

        //杀死进程，防止再此进入app点击控件没有反应
        System.exit(0);
    }

}
